package com.example.qggoodsconsumer.service.impl;

import com.example.qgcommon.util.Constants;
import com.example.qgcommon.util.IdWorker;
import com.example.qgcommon.util.RedisUtil;
import com.example.qggoodsconsumer.feign.GoodsFeign;
import com.example.qggoodsconsumer.feign.OrderFeign;
import com.example.qggoodsconsumer.service.LocalGoodsService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.annotation.Id;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
@Transactional
public class LocalGoodsServiceImpl implements LocalGoodsService {


    @Resource
    private GoodsFeign feign;

    @Resource
    private OrderFeign orderFeign;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private RabbitTemplate rabbitTemplate;


    @Override
    public List<Map> getAllGoods() {
        return feign.getAllGoods();
    }

    @Override
    public List<Map> getAllGoodsByQgTotal() {
        return feign.getAllGoodsByQgTotal();
    }


//    @Override
    //使用rabbit
    public  int  qg(Map map) {

        int goodsId = Integer.parseInt((String) map.get( "goodsId" ));

        int userId =(Integer) map.get( "userId" );

        //首先查看redis中是否有对应的抢购记录
        //有则直接返回不能在抢购信息
        if (redisUtil.exist("qgsucess:"+goodsId+":"+userId)){
            return -1;
        }

      //直接把抢购信息发给信息队列
        rabbitTemplate.convertAndSend("myqg7",map);

        return 1;
    }

    @Override
    public int getQgResult(Map map) {
        //根据用户名和商品id获得抢购数量
        int count = feign.getCountByGoodsIdUid( map );
        if (count==1){
            //抢购成功
            return count;
        }else{
            //判断抢购活动是否结束
            int goodsId = Integer.parseInt((String) map.get( "goodsId" ));
            //获取原始库存
            int stock = feign.getStock( goodsId );
            //获取已抢购数
            int qgTotalByGoodsId = feign.getQgTotalByGoodsId( goodsId );

            if (stock<=qgTotalByGoodsId){
                //抢购已结束
                return -2;
            }else{
                //抢购未结束
                return 0;
            }
        }

    }

//    @Override
//    public Map getById(int goodsId) {
//        return ;
//    }

//    @Override
//    public int getCountByGoodsIdUid(Map map) {
//        return ;
//    }

    @RabbitListener(queues = "myqg7")
    public  void  getMsg(Map map) {

       int goodsId = Integer.parseInt((String) map.get( "goodsId" ));

        int userId = (Integer) map.get( "userId" );
       //获取原始库存
        int stock = feign.getStock( goodsId );
        //获取已抢购数
        int qgTotalByGoodsId = feign.getQgTotalByGoodsId( goodsId );

        if (stock>qgTotalByGoodsId){
            //发现原始库存数不大于抢购数的请求，去抢分布式锁
            //使用分布式锁
//                                                (long) 40
            //当没有获得分布式锁，继续循环
            while(!redisUtil.lock("mylock", 40L ));

                //获取已抢购数
                 qgTotalByGoodsId = feign.getQgTotalByGoodsId( goodsId );
                //再次判断是否
                if (stock>qgTotalByGoodsId){
                    //可以抢购
                    int stockId = feign.addTempSotck(map);
                    System.out.println("stockId:"+stockId);

                    //在抢购成功后，把记录写入reids
                    redisUtil.setStr( "qgsucess:"+goodsId+":"+userId,"1" );



                    //唯一的字符串
                    //   UUID.randomUUID().toString();
                    //生成订单
                    //订单编号
                    //把对应的临时库存表存入到orderMap中
                    Map orderMap = new HashMap();
                    orderMap.putAll(map);

                    String orderId = IdWorker.getId();
                    orderMap.put("id",orderId);
                    orderMap.put("orderNo",orderId);
                    orderMap.put("stockId",stockId);

                    //根据goodsId查询商品
                    Map goodsMap = feign.getById(Integer.parseInt( (String) map.get( "goodsId" ) ) );
                    orderMap.put("num",1);
                    orderMap.put("amount",(Double)goodsMap.get("price"));
                    //支付状态 (0:待支付 1：支付成功 2：支付失败)
                    orderMap.put("status", Constants.READY_PAY );

                    //保存订单
                    orderFeign.addOrder(orderMap);

                }
                //释放锁
            redisUtil.unLock("mylock");
            }
//        }
    }




//        @Override
//    public  int  qg(Map map) {
//        int re = -1;
//       int goodsId = Integer.parseInt((String) map.get( "goodsId" ));
//       //获取原始库存
//        int stock = feign.getStock( goodsId );
//        //获取已抢购数
//        int qgTotalByGoodsId = feign.getQgTotalByGoodsId( goodsId );
//
//        //判断是否能够抢购
//        //可能多线程，运行到当前位置
//        try{
//            Thread.sleep( 100 );
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        if (stock>qgTotalByGoodsId){
//            //发现原始库存数不大于抢购数的请求，去抢分布式锁
//            //使用分布式锁
////                                                (long) 40
//            //当没有获得分布式锁，继续循环
//            while(!redisUtil.lock("mylock", 40L ));
//
//                //获取已抢购数
//                 qgTotalByGoodsId = feign.getQgTotalByGoodsId( goodsId );
//                //再次判断是否
//                if (stock>qgTotalByGoodsId){
//                    //可以抢购
//                    re = feign.addTempSotck( map );
//                }
//                //释放锁
//            redisUtil.unLock("mylock");
//            }
////        }
//        return re;
//    }



//    @Override
    //使用syn
//    public  int  qg(Map map) {
//        int re = -1;
//       int goodsId = Integer.parseInt((String) map.get( "goodsId" ));
//       //获取原始库存
//        int stock = feign.getStock( goodsId );
//        //获取已抢购数
//        int qgTotalByGoodsId = feign.getQgTotalByGoodsId( goodsId );
//
//        //判断是否能够抢购
//        //可能多线程，运行到当前位置
//        try{
//            Thread.sleep( 100 );
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        if (stock>qgTotalByGoodsId){
//            //发现可以抢购的请求，进行排队
//            //发现原始库存数不大于抢购数的请求，则不需要排队
////            synchronized(this){
//            //使用分布式锁
//
//
//                 qgTotalByGoodsId = feign.getQgTotalByGoodsId( goodsId );
//                //再次判断是否
//                if (stock>qgTotalByGoodsId){
//                    //可以抢购
//                    re = feign.addTempSotck( map );
//                }
////            }
//        }
//        return re;
//    }

}
